# Maintainer: Wu Zhenyu <wuzy01@qq.com>
_realname=bottom

pkgbase=mingw-w64-$_realname
pkgname=$MINGW_PACKAGE_PREFIX-$_realname
pkgver=0.9.0
pkgrel=2
pkgdesc="A graphical process/system monitor (mingw-w64)"
url="https://github.com/ClementTsang/bottom"
arch=(any)
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
license=('MIT')
makedepends=($MINGW_PACKAGE_PREFIX-rust tree)
source=("$url/archive/$pkgver/$_realname-$pkgver.tar.gz"
        "$url/releases/download/$pkgver/completion.tar.gz"
        "$url/releases/download/$pkgver/manpage.tar.gz"
        "ntapi-link-ntdll-arm64.patch")
sha256sums=('0b5ba825905748a6146307517cf5e148bbc7ce13070a8448cc2d38ee68c1a42c'
            'ba822566046e1f0e1300399e25d134feba79ebe8d0b35f8c3a90f847a8e2b220'
            '38cfa611b76f1e92be20ccbf21a6f3a83cbf9a20f93a032e5307338e5747e272'
            '4a6a64884fd7e3da96b1df71adfe12fc909cd85470eb382d6282f5e2b5645fe1')

prepare() {
  cd "$_realname-$pkgver"
  cargo vendor \
    --locked \
    --versioned-dirs

  mkdir -p .cargo
  cat >> .cargo/config.toml <<END

[source.crates-io]
replace-with = "vendored-sources"

[source.vendored-sources]
directory = "vendor"
END


  sed -i -e 's/"cfg(all(target_arch = \\"\([^\\]\+\)\\", target_env = \\"gnu\\", target_abi = \\"llvm\\", not(windows_raw_dylib)))"/"\1-pc-windows-gnullvm"/g' \
    "vendor/windows-targets-0.48.0/Cargo.toml"
  sed -i -e 's/\("Cargo.toml":\)"[^"]\+"/\1"'"$(sha256sum "vendor/windows-targets-0.48.0/Cargo.toml" | cut -d' ' -f1)"'"/' \
    "vendor/windows-targets-0.48.0/.cargo-checksum.json"
  patch -d vendor/ntapi-0.4.1 -Np1 -i "${srcdir}/ntapi-link-ntdll-arm64.patch"
}

build() {
  cd "$_realname-$pkgver"
  cargo build --frozen --release --all-features
}

check() {
  cd "$_realname-$pkgver"
  CARGO_HUSKY_DONT_INSTALL_HOOKS=true cargo test --frozen --all-features
}

package() {
  cd "$_realname-$pkgver"

  # binary
  install -vDm755 -t "$pkgdir$MINGW_PREFIX/bin" target/release/btm

  # license
  install -vDm644 -t "$pkgdir$MINGW_PREFIX/share/licenses/$_realname" LICENSE

  # documentation
  install -vDm644 -t "$pkgdir$MINGW_PREFIX/share/doc/$_realname" *.md
  cp -r docs sample_configs "$pkgdir$MINGW_PREFIX/share/doc/$_realname"
  rm "$pkgdir$MINGW_PREFIX/share/doc/bottom/docs/.gitignore"

  cd "${srcdir}"
  # manpage
  install -Dm644 btm.1.gz "$pkgdir$MINGW_PREFIX/share/man/man1/btm.1.gz"

  # completions
  install -Dm644 _btm "$pkgdir$MINGW_PREFIX/share/zsh/site-functions/_btm"
  install -Dm644 btm.bash "$pkgdir$MINGW_PREFIX/share/bash-completion/completions/btm"
  install -Dm644 btm.fish "$pkgdir$MINGW_PREFIX/share/fish/vendor_completions.d/btm.fish"
}
